<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" style="width: 900px;">
    <el-form
      ref="formRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="中标客户" prop="customerId" class="half-box">
        <el-select
          v-model="formData.customerId"
          clearable
          filterable
          disabled
          collapse-tags
          class="!w-200px"
          placeholder="请选择中标客户"
        >
          <el-option
            v-for="item in cusList"
            :key="item.id"
            :label="item.companyName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="产品类别" prop="coalId" class="half-box">
        <el-select
          v-model="formData.coalId"
          clearable
          filterable
          disabled
          collapse-tags
          class="!w-200px"
          placeholder="请选择产品类别"
        >
          <el-option
            v-for="item in coalTypeList"
            :key="item.id"
            :label="item.coalName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="关联客户" prop="relationCustomerId" class="half-box">
        <el-select
          v-model="formData.relationCustomerId"
          clearable
          filterable
          collapse-tags
          class="!w-200px"
          placeholder="请选择关联客户"
          @change="handleRelationCustomerChange"
        >
          <el-option
            v-for="item in relCusData"
            :key="item.id"
            :label="item.cusName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="关联产品" prop="relationCoalId" class="half-box">
        <el-select
          v-model="formData.relationCoalId"
          clearable
          filterable
          collapse-tags
          class="!w-200px"
          placeholder="请选择关联产品"
          @change="handleRelationCoalChange"
        >
          <el-option
            v-for="item in relCoalList"
            :key="item.proId"
            :label="item.proName"
            :value="item.proId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime" class="half-box">
        <el-date-picker
          v-model="formData.startTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择开始时间"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime" class="half-box">
        <el-date-picker
          v-model="formData.endTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择结束时间"
        />
      </el-form-item>
      <div style="clear: both;"></div>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark"
                  type="textarea"
                  style="width: 630px;"
                  maxlength="200"
                  show-word-limit
                  placeholder="请输入备注"/>
      </el-form-item>
      <el-button
        type="primary"
        plain
        @click="handleExport"
        :loading="exportLoading"
        v-hasPermi="['bid:agreement:export']"
      >
        价格由高到低排序
      </el-button>
      <el-button
        type="primary"
        plain
        @click="handleHaulCapacity"
        :loading="haulCapacityLoading"
        v-hasPermi="['bid:agreement:haulCapacity']"
      >
        价格由低到高排序
      </el-button>
      <el-table
        v-loading="loading"
        :data="list"
        border
        stripe
        show-summary
        :summary-method="getSummary"
        :header-cell-style="{ background: '#F3F4F7', color: '#555' }"
        style="margin-top: 20px"
      >
        <el-table-column label="序号" align="center" min-width="60" fixed="left">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          label="标段号"
          align="center"
          prop="markCode"
          min-width="110"
          fixed="left"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="计划运量(吨)" align="center" prop="bidAmount" min-width="100"/>
        <el-table-column label="价格(元)" align="center" prop="bidPrice" min-width="100"/>
      </el-table>
    </el-form>
    <div style="clear: both;"></div>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as performance from '@/api/performance'
import {dateFormatter} from '@/utils/formatTime'
import * as Utils from '@/utils/dict'
import * as announceManage from "@/api/announceManage";
import * as dataCenter from "@/api/dataCenter";
import * as pushJiLiang from "@/api/pushJiLiang";

const {DICT_TYPE, getDictLabel} = reactive(Utils)
const emit = defineEmits(['success'])
const formRef = ref()
const {t} = useI18n()
const message = useMessage()
const dialogVisible = ref(false)
const dialogTitle = ref('')
const loading = ref(false)
const formLoading = ref(false)
const list = ref([])
const formData = ref({
  customerId: undefined,
  customerName: undefined,
  coalId: undefined,
  coalName: undefined,
  relationCustomerId: undefined,
  relationCustomerName: undefined,
  relationCoalId: undefined,
  relationCoalName: undefined,
  startTime: undefined,
  endTime: undefined,
  remark: undefined,
  relId: undefined
})
let validStarTime = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('开始时间不能为空'))
  } else {
    const now = new Date()
    const selectedTime = new Date(value)
    if (selectedTime < now) {
      callback(new Error('开始时间不能小于当前时间'))
    } else {
      callback()
    }
  }
}
let validEndTime = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('结束时间不能为空'))
  } else {
    const startTime = formData.value.startTime
    if (startTime && value && new Date(value) < new Date(startTime)) {
      callback(new Error('结束时间不能小于开始时间'))
    } else {
      callback()
    }
  }
}
const formRules = reactive({
  relationCustomerId: [{required: true, message: '关联客户不能为空', trigger: 'change'}],
  relationCoalId: [{required: true, message: '关联产品不能为空', trigger: 'blur'},{
    validator: (rule, value, callback) => {
      if (!formData.value.relationCustomerId) {
        callback(new Error('请先选择关联客户'))
      } else {
        callback()
      }
    },
    trigger: 'change'
  }],
  startTime: [{required: true,validator: validStarTime, trigger: 'change'}],
  endTime: [{required: true, validator: validEndTime, trigger: 'change'}],
})
const relCusData =ref()
const open = async (data,relCusList) => {
  resetFn()
  relCusData.value = relCusList
  relCoalList.value = []
  dialogVisible.value = true
  dialogTitle.value = '一键推送'
  if (!data || data.length === 0) return
  const firstItem = data[0]
  // 设置表单字段
  formData.value = {
    customerId: firstItem.customerId,
    customerName: firstItem.customerName,
    coalId: firstItem.coalId,
    coalName: firstItem.coalName
  }
  // 设置表格数据
  list.value = data.map(item => ({
    id: item.id,
    markCode: item.markCode,
    bidAmount: item.bidAmount,
    bidPrice: item.bidPrice
  }))
}
const getSummary = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }

    const values = data.map(item => Number(item[column.property]))

    switch (column.property) {
      case 'bidAmount':
        // 计划运量总和
        sums[index] = values.reduce((a, b) => a + b, 0)
        break
      case 'bidPrice':
        // 改为显示：总价 = 运量 × 单价 的总和
        let totalPrice = 0
        data.forEach(item => {
          totalPrice += item.bidAmount * item.bidPrice
        })
        // 暂不计算
        sums[index] = `总价：0`
        break
      default:
        // 其他列保持默认处理
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            return prev + (isNaN(value) ? 0 : value)
          }, 0)
        } else {
          sums[index] = ''
        }
    }
  })
  return sums
}
// 合计计算
const total = computed(() => {
  const bidAmountTotal = list.value.reduce((sum, item) => sum + item.bidAmount, 0)
  const bidPriceTotal = list.value.reduce((sum, item) => sum + item.bidPrice, 0)
  return { bidAmountTotal, bidPriceTotal }
})

// 排序：价格由高到低
const handleExport = () => {
  list.value.sort((a, b) => b.bidPrice - a.bidPrice)
}

// 排序：价格由低到高
const handleHaulCapacity = () => {
  list.value.sort((a, b) => a.bidPrice - b.bidPrice)
}
/** 提交表单 */
const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  try {
    formLoading.value = true

    // 获取选中的关联客户名称
    const selectedCus = relCusData.value.find(
      item => item.id === formData.value.relationCustomerId
    )
    const selectedCoal = relCoalList.value.find(
      item => item.proId === formData.value.relationCoalId
    )
    console.log(list.value)
    // 构造最终提交的数据
    const submitData = {
      ...formData.value,
      relationCustomerName: selectedCus?.cusName || '',
      relationCoalName: selectedCoal?.proName || '',
      sectionInfoVOList: list.value.map((item,index) => ({
        serialNum: index + 1,
        markCode: item.markCode,
        bidAmount: item.bidAmount,
        bidPrice: item.bidPrice,
        id: item.id
      }))
    }
    await pushJiLiang.pushMetering(submitData)
    message.success(t('common.operateSuccess'))
    dialogVisible.value = false
    resetFn()
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 获取客户列表 */
const cusList =ref()
const getCustomList = async () => {
  const data = await announceManage.getAllList()
  cusList.value = data || []
}
/** 获取产品列表 */
const coalTypeList: Record<string, any> = ref([])
const bidCoalManageList = async () => {
  const res = await dataCenter.bidCoalManageList()
  coalTypeList.value = res || []
}

const handleRelationCustomerChange = async (cusId) => {
  // 清空已选产品
  formData.value.relationCoalId = undefined
  relCoalList.value = []

  if (cusId) {
    await getRelationCoalName(cusId)
  }
}
const handleRelationCoalChange = (proId) => {
  const selectedProduct = relCoalList.value.find(item => item.proId === proId)
  if (selectedProduct) {
    formData.value.relId = selectedProduct.id
  }
}
/** 获取关联产品列表 */
const relCoalList = ref([])
const getRelationCoalName = async (cusId) => {
  if (!cusId) return
  try {
    const res = await pushJiLiang.getRelationCoalName({ cusId })
    relCoalList.value = res || []
  } catch (error) {
    message.error('获取关联产品失败')
  }
}

const resetFn = () => {
  formData.value = {
    customerId: undefined,
    customerName: undefined,
    coalId: undefined,
    coalName: undefined,
    relationCustomerId: undefined,
    relationCustomerName: undefined,
    relationCoalId: undefined,
    relationCoalName: undefined,
    startTime: undefined,
    endTime: undefined,
    remark: undefined,
    relId: undefined
  }
  formRef.value?.resetFields()
}
/** 初始化 **/
onMounted(async () => {
  await getCustomList()
  await bidCoalManageList()
})
defineExpose({ open })
</script>
